/*********************************************************************
 *
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2020 Shivang Patel
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Willow Garage, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 * Author: Shivang Patel
 *
 * Reference tutorial:
 * https://navigation.ros.org/tutorials/docs/writing_new_nav2planner_plugin.html
 *********************************************************************/

#ifndef NAV2_STRAIGHTLINE_PLANNER__STRAIGHT_LINE_PLANNER_HPP_
#define NAV2_STRAIGHTLINE_PLANNER__STRAIGHT_LINE_PLANNER_HPP_

#include <string>
#include <memory>
#include <list>

#include "rclcpp/rclcpp.hpp"
#include "geometry_msgs/msg/point.hpp"
#include "geometry_msgs/msg/pose_stamped.hpp"

#include "nav2_core/global_planner.hpp"
#include "nav_msgs/msg/path.hpp"
#include "nav2_util/robot_utils.hpp"
#include "nav2_util/lifecycle_node.hpp"
#include "nav2_costmap_2d/costmap_2d_ros.hpp"
#include "nav_msgs/srv/get_map.hpp"
#include "nav2_msgs/srv/get_map_nav2.hpp"

#include "full_coverage_path_planner_ros2/common.h"

// #define DEBUG_PLOT

#ifndef dabs
#define dabs(a)     ((a) >= 0 ? (a):-(a))
#endif
#ifndef dmin
#define dmin(a, b)   ((a) <= (b) ? (a):(b))
#endif
#ifndef dmax
#define dmax(a, b)   ((a) >= (b) ? (a):(b))
#endif
#ifndef clamp
#define clamp(a, lower, upper)    dmax(dmin(a, upper), lower)
#endif

enum
{
  eDirNone = 0,
  eDirRight = 1,
  eDirUp = 2,
  eDirLeft = -1,
  eDirDown = -2,
};

namespace full_coverage_path_planner
{

class FullCoveragePath : public nav2_core::GlobalPlanner
{
public:
  FullCoveragePath();
  ~FullCoveragePath();

  // plugin configure
  void configure(
    const rclcpp_lifecycle::LifecycleNode::WeakPtr & parent,
    std::string name, std::shared_ptr<tf2_ros::Buffer> tf,
    std::shared_ptr<nav2_costmap_2d::Costmap2DROS> costmap_ros) override;

  // plugin cleanup
  void cleanup() override;

  // plugin activate
  void activate() override;

  // plugin deactivate
  void deactivate() override;

  // This method creates path for given start and goal pose.
  nav_msgs::msg::Path createPlan(
    const geometry_msgs::msg::PoseStamped & start,
    const geometry_msgs::msg::PoseStamped & goal) override;


public:
  /**
   * Find a path that spirals inwards from init until an obstacle is seen in the grid
   * @param grid 2D grid of bools. true == occupied/blocked/obstacle
   * @param init start position
   * @param visited all the nodes visited by the spiral
   * @return list of nodes that form the spiral
   */
  static std::list<gridNode_t> spiral(std::vector<std::vector<bool> > const &grid, std::list<gridNode_t> &init,
                                      std::vector<std::vector<bool> > &visited);
  /**
   * Perform Spiral-STC (Spanning Tree Coverage) coverage path planning.
   * In essence, the robot moves forward until an obstacle or visited node is met, then turns right (making a spiral)
   * When stuck in the middle of the spiral, use A* to get out again and start a new spiral, until a* can't find a path to uncovered cells
   * @param grid
   * @param init
   * @return
   */
  static std::list<Point_t> spiral_stc(std::vector<std::vector<bool> > const &grid,
                                        Point_t &init,
                                        int &multiple_pass_counter,
                                        int &visited_counter);
  /**
   * Convert ROS Occupancy grid to internal grid representation, given the size of a single tile
   * @param cpp_grid_ ROS occupancy grid representation. Cells higher that 65 are considered occupied
   * @param grid internal map representation
   * @param tileSize size (in meters) of a cell. This can be the robot's size
   * @param realStart Start position of the robot (in meters)
   * @param scaledStart Start position of the robot on the grid
   * @return success
   */
  bool parseGrid(nav_msgs::msg::OccupancyGrid const& cpp_grid_,
                 std::vector<std::vector<bool> >& grid,
                 float robotRadius,
                 float toolRadius,
                 geometry_msgs::msg::PoseStamped const& realStart,
                 Point_t& scaledStart);
  /**
   * Convert internal representation of a to a ROS path
   * @param start Start pose of robot
   * @param goalpoints Goal points from Spiral Algorithm
   * @param plan  Output plan variable
   */
  void parsePointlist2Plan(const geometry_msgs::msg::PoseStamped& start, std::list<Point_t> const& goalpoints,
                           std::vector<geometry_msgs::msg::PoseStamped>& plan);



private:
  // TF buffer
  std::shared_ptr<tf2_ros::Buffer> tf_;

  // node ptr
  nav2_util::LifecycleNode::SharedPtr node_;

  // Global Costmap
  nav2_costmap_2d::Costmap2D * costmap_;

  // The global frame of the costmap
  std::string global_frame_, name_;

  double interpolation_resolution_;
  float robotRadius;
  float toolRadius;
  float tile_size_;
  fPoint_t grid_origin_;
  rclcpp::Client<nav2_msgs::srv::GetMapNav2>::SharedPtr cpp_grid_client_;
  geometry_msgs::msg::PoseStamped previous_goal_;

  struct spiral_cpp_metrics_type
  {
    int visited_counter;
    int multiple_pass_counter;
    int accessible_counter;
    double total_area_covered;
  };
  spiral_cpp_metrics_type spiral_cpp_metrics_;
};

}  // namespace full_coverage_path_planner

#endif  // NAV2_STRAIGHTLINE_PLANNER__STRAIGHT_LINE_PLANNER_HPP_
